from django.shortcuts import render, HttpResponse
import pymysql
import redis
import json
from .compareImage import *
import keras
import tensorflow as tf

# Create your views here.
# 创建MySQL连接
mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8')
cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)

# 创建redis连接
redis_conn_6389 = redis.Redis(host='127.0.0.1', port=6389)

# 读入模型
graph = tf.get_default_graph()
model_name = '../../image_scene_classification_vgg16_3.h5'  # 修改自己的路径
base_net = keras.models.load_model(model_name)


def home(request):
    pass


def model_predict(img, types):
    global graph
    global base_net
    # 数据处理
    img = deal_image(img, types)

    if (type(img) == 'list' and not img):
        return []
    img = cv2.resize(img, (224, 224))
    img = img[..., ::-1]

    x = img / 255
    x = np.expand_dims(x, axis=0)

    # 图像预测
    with graph.as_default():
        predict = base_net.predict(x)
    predict[predict < 0.2] = 0
    predict_top3 = predict.argsort(axis=1)[:, -3:]

    # 加载类别标签
    with open('./explore/targets.json', encoding='utf-8') as f:
        targets = json.load(f)

    # 处理结果
    result = []
    for order in predict_top3[0]:
        if predict[0][order]:
            result.append(targets[str(order)])

    print(' '.join(result))
    return result


def recognition(request):
    '''

    :param request: types：本地上传为1，网络地址为0
    :return: 图片所属的电影，以及可能出现的时间点
    '''
    result = {'status': 200}

    # 处理目标图片
    types = int(request.POST.get('types'))
    if types == 1:
        target_img = request.FILES.get('img')
    else:
        target_img = request.POST.get('img')

    # 目标图片人物检测
    pictures_id = set()
    persons = get_image_person(target_img, types)
    for person in persons:
        pictures_id |= redis_conn_6389.smembers(person)
    print(pictures_id)
    # 目标图片场景检测
    sence = model_predict(target_img, types)
    sence_picture_id = redis_conn_6389.sinter(sence + [-1, -2])
    if pictures_id & sence_picture_id:
        pictures_id &= sence_picture_id

    # 如果未找到分类场景，返回空
    if not pictures_id:
        result['status'] = 404
        return HttpResponse(json.dumps(result))

    # 处理所有可能的picture_id
    pictures_id = set(map(lambda x: int(x.decode()), pictures_id))

    # 从数据库中读取所有图片
    images_info = []
    sql = "select * from picture_t_picture where id in %s" % repr(tuple(pictures_id | {-1, -2}))
    try:
        cursor.execute(sql)
        images_info = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    # 测试
    # images_info = []
    # sql = "select * from t_picture"
    # try:
    #     cursor.execute(sql)
    #     images_info = cursor.fetchall()
    # except:
    #     print(sql)
    #     result['status'] = 500

    for img_info in images_info:
        # 比对两张图片相似度，> 90% 返回该图片信息
        if compare_image(target_img, img_info['url'], types):
            result['info'] = img_info
            result['info']['persons'] = persons
            print(result)
            return HttpResponse(json.dumps(result))

    # 未找到类似图片，返回状态码404
    if result['status'] != 500:
        result['status'] = 404

    return HttpResponse(json.dumps(result))
